var map;
var receivedData = [];

$(document).ready(function () {
    initializaMap();
    loadMarkers();
});

function initializaMap() {
    var mapOptions = {
        center: new google.maps.LatLng(40.193244, -8.411675),
        zoom: 15,
        panControl: true,
        zoomControl: true,
        mapTypeControl: false,
        scaleControl: true,
        streetViewControl: false,
        overviewMapControl: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);

    google.maps.event.addListener(map, 'click', function (event) {
        getPossibleLocations(event.latLng.k, event.latLng.D, function (rdata) {
            var data = rdata.address;
            receivedData = rdata;
            $('#teste')
                    .find('option')
                    .remove();

            for (var i in data) {
                var s = '<option value=' + i + '>'
                        + buildAddress(data, i)
                        + (!data[i].country ? '' : data[i].country)
                        + '</option>';
                $('#teste')
                        .find('option')
                        .end()
                        .append(s);
            }
        });
    });
}

function loadMarkers() {
    getAllAddress(function (data) {
        for (var i in data) {
            addMarker(data[i].address, data[i].lat, data[i].log);
        }
    });
}

function addMarker(title, lat, lng) {
    var myLatlng = new google.maps.LatLng(lat, lng);
    var marker = new google.maps.Marker({
        position: myLatlng,
        map: map,
        title: title
    });
}

function buildAddress(data, i) {
    return (!data[i].neighborhood ? '' : data[i].neighborhood + ', ')
            + (!data[i].route ? '' : data[i].route + ', ')
            + (!data[i].administrative_area_level_3 ? '' : data[i].administrative_area_level_3 + ', ')
            + (!data[i].administrative_area_level_2 ? '' : data[i].administrative_area_level_2 + ', ')
            + (!data[i].administrative_area_level_1 ? '' : data[i].administrative_area_level_1 + ', ')
            + (!data[i].postal_code ? '' : data[i].postal_code + ', ');
}

function addLocationClick(eventObject) {
    if (receivedData) {
        if ($('#teste').val() === '-1') {
            return;
        }
        var address = buildAddress(receivedData.address, $('#teste').val());
        var countryName = receivedData.address[$('#teste').val()].country;

        sendCreateAddress(countryName, address, receivedData.lat, receivedData.lng, function (data) {
            if(data['success']) {
                addMarker(address, receivedData.lat, receivedData.lng);
            }
        });
    }
}